package gri_roles_config;

use xml_helper;
use Data::Dumper;

my $error="";

sub new {
my $self={};
shift;
my $f=shift;

	$self->{xml_helper}=new xml_helper();
	$self->{filename}=$f;

	my $d=""; my $fd;
	if(!open($fd,$f)) {
		$error="Can not open file '$f' : $!";
		return(undef);
	}
	$d=join("",<$fd>);
	close($fd);
	my $x=$self->{xml_helper}->parse($d);
	if(! $x) {
		$error="Unable to parse XML!";
		return undef;
	}

	# Check the data is in the format we expect.

	my ($data,$attrs,$elements)=$self->{xml_helper}->get_element("");
	if(!defined($data)) {
		$error="Invalid data to parse [top level]";
		return(undef);
	}
	if(scalar(@$elements)!=1) {
		$error="More than 1 top level element!";
		return(undef);
	}
	if($elements->[0] ne "|gri_roles_config#0") {
		$error="Top level element is '$elements->[0]' - should be '|gri_roles_config#0'";
		return(undef);
	}
	($data,$attrs,$elements)=$self->{xml_helper}->get_element("gri_roles_config#0");
	if(!defined($data)) {
		$error="Invalid data to parse [gri_roles_config#0]";
		return(undef);
	}
	#################################################################
	# We expect 1 or more roles to be defined. Abort if not.	#
	#################################################################
	if(! grep {$_ eq "gri_roles_config#0|role#0"} @$elements) {
		$error="Missing 'role' element.";
		return(undef);
	}
	my $crole=0;
	$self->{roles}=[];
	while(1) {
		($data,$attrs,$elements)=$self->{xml_helper}->get_element("gri_roles_config#0|role#$crole");
		last if !defined($data);
		my @E=qw(name title description);
		#########################################################
		# Check mandatory attributes exist.			#
		#########################################################
		for my $cattr (@E) {
			if(!exists($attrs->{$cattr})) {
				$error="Missing attribute '$cattr' for element 'role' - number " . $crole+1 . ".";
				return(undef);
			}
		}
		#########################################################
		# Check no unrecognised attributes exist.		#
		#########################################################
		for my $cattr (keys %$attrs) {
			if(! grep {$_ eq $cattr} @E) {
				$error="Found unrecognised attribute '$cattr' for element 'role' - number " . $crole+1 . ".";
				return(undef);
			}
		}
		push @{$self->{roles}},{name => $attrs->{name}, title => $attrs->{title}, description => $attrs->{description}};
		$crole++;
	}
	bless($self);
	return $self;
}

sub get_role_list {
my $self=shift;
	my @R=();

	for my $crole (@{$self->{roles}}) {
		push @R,$crole->{name};
	}
	return @R;
}

sub get_role_details {
my $self=shift;
my $role=shift;

	for my $crole (@{$self->{roles}}) {
		if($crole->{name} eq $role) {
			return ($crole->{title},$crole->{description});
		}
	}
	return (undef,undef);
}

sub error {
	return $error;
}

1;

